package yxy.cherry.game.base.bean;

import java.util.Collection;
import java.util.HashSet;
import java.util.concurrent.TimeUnit;

import org.redisson.api.RLock;
import org.redisson.api.RSet;

import yxy.apple.util.redisson.RedisConnection;
import yxy.apple.util.redisson.RedisException;

public class GatewayUrl {

	// redis==========================================================================

	static public String key() {
		return "gwurls";
	}

	static public RSet<String> touch(RedisConnection redis) throws RedisException {
		if (redis.ready()) {
			try {
				return redis.client().getSet(key());
			} catch (Exception e) {
				throw new RedisException(e);
			}
		} else {
			throw new RedisException("无可用Redis连接!");
		}
	}

	static public Collection<String> all(RedisConnection redis) {
		try {
			return touch(redis).readAll();
		} catch (RedisException e) {
			e.printStackTrace();
		}
		return new HashSet<>();
	}

	static public void regist(RedisConnection redis, String url) {
		RLock lock = lock(redis);
		try {
			if (lock.tryLock(10, 5, TimeUnit.SECONDS)) {
				touch(redis).add(url);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
	}

	static public void logout(RedisConnection redis, String url) {
		RLock lock = lock(redis);
		try {
			if (lock.tryLock(10, 5, TimeUnit.SECONDS)) {
				touch(redis).remove(url);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
	}

	static private RLock lock(RedisConnection redis) {
		return redis.client().getLock(key() + "_lock");
	}
}
